﻿using System;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using WpfApp1.Model;

namespace WpfApp1.ViewModel
{
    class RulesViewModel
    {
        private string dict_select;
        private long dict_select_id;
        private ObservableCollection<Rule> rules;

        public string Dict_select { get => dict_select; set => dict_select = value; }
        internal ObservableCollection<Rule> Rules { get => rules; set => rules = value; }
        public long Dict_select_id { get => dict_select_id; set => dict_select_id = value; }

        public RulesViewModel()
        {
            rules = new ObservableCollection<Rule>();
            string sql_init = "create table if not exists select_dic(id INTEGER PRIMARY KEY AUTOINCREMENT,directorypath nvarchar(255),is_last INTEGER(2))";
            SQLiteCommand command = new SQLiteCommand(sql_init, MainWindow.connection);
            command.ExecuteNonQuery();

            SetModel();
        }

        private void SetModel()
        {
            string sql_rules = "select id, prefix, directorypath from rules";
            SQLiteCommand command = new SQLiteCommand(sql_rules, MainWindow.connection);
            SQLiteDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                rules.Add(new Rule()
                {
                    Id = (long)reader["id"],
                    Prefix = reader["prefix"].ToString(),
                    Directorypath = reader["directorypath"].ToString()
                });
            }

            string sql_select = "select id,directorypath from select_dic where is_last=1 limit 1";
            command = new SQLiteCommand(sql_select, MainWindow.connection);
            reader = command.ExecuteReader();
            if (reader.Read())
            {
                dict_select = reader["directorypath"].ToString();
                dict_select_id = (long)reader["id"];
            }
            else
            {
                dict_select = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                dict_select_id = 0;
            }

        }
    }
}
